<template>
  <div class="app-container">
    <!-- 搜索和新增区域 -->
    <el-card>
      <el-row :gutter="20">
        <el-col :span="6">
          <el-input v-model="queryParams.structureName" placeholder="请输入构筑物名称" clearable @clear="handleFilter"
            @keyup.enter="handleFilter" />
        </el-col>
        <el-col :span="6">
          <el-select v-model="queryParams.structureType" placeholder="请选择构筑物类型" clearable @change="handleFilter">
            <el-option v-for="item in structureTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleFilter">查询</el-button>
          <el-button @click="resetFilter">重置</el-button>
        </el-col>
      </el-row>
    </el-card>
    <el-card class="mt-1">
      <el-button type="primary" @click="showAddDialog">+新增构筑物</el-button>
      <!-- 构筑物表格 -->
      <el-table  :data="structureList" border style="width: 100%" class="mt-2" v-loading="loading">
        <el-table-column prop="structureName" label="构筑物名称" width="180" align="center" />
        <el-table-column prop="structureNumber" label="编号" width="120" align="center" />
        <el-table-column prop="structureType" label="类型" width="150" align="center" />
        <el-table-column prop="remark" label="描述" align="center" />
        <el-table-column label="操作" width="180" align="center" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleEdit(scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="mt-2">
        <el-pagination v-model:current-page="queryParams.pageNum" v-model:page-size="queryParams.pageSize"
          :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper" :total="total"
          @size-change="handleSizeChange" @current-change="handleCurrentChange" />
      </div>
    </el-card>

    <!-- 新增构筑物对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增构筑物" width="50%">
      <el-form :model="addForm" label-width="120px" :rules="rules" ref="addFormRef">
        <el-form-item label="构筑物名称" prop="structureName">
          <el-input v-model="addForm.structureName" placeholder="请输入构筑物名称" />
        </el-form-item>
        <el-form-item label="编号" prop="structureNumber">
          <el-input v-model="addForm.structureNumber" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="类型" prop="structureType">
          <el-select v-model="addForm.structureType" placeholder="请选择类型" style="width: 100%">
            <el-option v-for="item in structureTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="addForm.remark" type="textarea" :rows="2" placeholder="请输入描述信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAdd">保存</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 编辑构筑物对话框 -->
    <el-dialog v-model="editDialogVisible" title="编辑构筑物" width="50%">
      <el-form :model="editForm" label-width="120px" :rules="rules" ref="editFormRef">
        <el-form-item label="构筑物名称" prop="structureName">
          <el-input v-model="editForm.structureName" placeholder="请输入构筑物名称" />
        </el-form-item>
        <el-form-item label="编号" prop="structureNumber">
          <el-input v-model="editForm.structureNumber" placeholder="请输入编号" />
        </el-form-item>
        <el-form-item label="类型" prop="structureType">
          <el-select v-model="editForm.structureType" placeholder="请选择类型" style="width: 100%">
            <el-option v-for="item in structureTypeOptions" :key="item.dictValue" :label="item.dictLabel"
              :value="item.dictValue" />
          </el-select>
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input v-model="editForm.remark" type="textarea" :rows="2" placeholder="请输入描述信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  getStructureTypeList,
  getStructureList,
  getStructureDetail,
  addStructure,
  updateStructure,
  deleteStructure
} from '@/api/prod_operate/sys_setting/basic/structure_setup'

// 加载状态
const loading = ref(false)

// 构筑物类型选项
const structureTypeOptions = ref([])

// 构筑物列表数据
const structureList = ref([])

// 总记录数
const total = ref(0)

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  structureName: undefined,
  structureType: undefined
})

// 新增表单
const addForm = reactive({
  structureName: '',
  structureNumber: '',
  structureType: '',
  remark: ''
})

// 编辑表单
const editForm = reactive({
  structureId: '',
  structureName: '',
  structureNumber: '',
  structureType: '',
  remark: ''
})

// 对话框控制
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)

// 表单引用
const addFormRef = ref(null)
const editFormRef = ref(null)

// 表单验证规则
const rules = reactive({
  structureName: [
    { required: true, message: '请输入构筑物名称', trigger: 'blur' }
  ],
  structureNumber: [
    { required: true, message: '请输入编号', trigger: 'blur' }
  ],
  structureType: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ]
})

// 初始化数据
const initData = async () => {
  try {
    loading.value = true

    // 获取构筑物类型列表
    const typeRes = await getStructureTypeList()
    structureTypeOptions.value = typeRes.data

    // 获取构筑物列表
    await fetchStructureList()
  } catch (error) {
    console.error('初始化数据失败:', error)
    ElMessage.error('初始化数据失败')
  } finally {
    loading.value = false
  }
}

// 获取构筑物列表
const fetchStructureList = async () => {
  try {
    loading.value = true
    const res = await getStructureList(queryParams)
    structureList.value = res.rows
    total.value = res.total
  } catch (error) {
    console.error('获取构筑物列表失败:', error)
    ElMessage.error('获取构筑物列表失败')
  } finally {
    loading.value = false
  }
}

// 处理查询
const handleFilter = () => {
  queryParams.pageNum = 1
  fetchStructureList()
}

// 重置查询条件
const resetFilter = () => {
  queryParams.structureName = undefined
  queryParams.structureType = undefined
  handleFilter()
}

// 处理分页大小变化
const handleSizeChange = (val) => {
  queryParams.pageSize = val
  fetchStructureList()
}

// 处理当前页变化
const handleCurrentChange = (val) => {
  queryParams.pageNum = val
  fetchStructureList()
}

// 显示新增对话框
const showAddDialog = () => {
  addForm.structureName = ''
  addForm.structureNumber = ''
  addForm.structureType = ''
  addForm.remark = ''
  addDialogVisible.value = true
}

// 确认新增
const confirmAdd = async () => {
  try {
    await addFormRef.value.validate()

    await addStructure(addForm)
    ElMessage.success('新增构筑物成功')
    addDialogVisible.value = false
    fetchStructureList()
  } catch (error) {
    console.error('新增构筑物失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 处理编辑
const handleEdit = async (row) => {
  try {
    loading.value = true
    const res = await getStructureDetail(row.structureId)
    Object.assign(editForm, res.data)
    editDialogVisible.value = true
  } catch (error) {
    console.error('获取构筑物详情失败:', error)
    ElMessage.error('获取构筑物详情失败')
  } finally {
    loading.value = false
  }
}

// 确认编辑
const confirmEdit = async () => {
  try {
    await editFormRef.value.validate()

    await updateStructure(editForm)
    ElMessage.success('修改构筑物成功')
    editDialogVisible.value = false
    fetchStructureList()
  } catch (error) {
    console.error('修改构筑物失败:', error)
    if (error.message) {
      ElMessage.error(error.message)
    }
  }
}

// 处理删除
const handleDelete = (row) => {
  ElMessageBox.confirm('确认删除该构筑物吗?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      await deleteStructure(row.structureId)
      ElMessage.success('删除成功')
      fetchStructureList()
    } catch (error) {
      console.error('删除构筑物失败:', error)
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    // 取消删除
  })
}

// 初始化
onMounted(() => {
  initData()
})
</script>

<style scoped>
.app-container {
  padding: 20px;
}

.el-pagination {
  margin-top: 20px;
  text-align: right;
}

.el-select {
  width: 100%;
}

.el-table {
  margin-top: 20px;
}

.el-input {
  width: 100%;
}
</style>